/*
 * The MIT License
 *
 * Copyright (c) 2009 André D. Piske
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */
package org.gohtml.tree;

import java.util.LinkedList;
import java.util.List;
import org.gohtml.AttributeSet;
import org.gohtml.NodeWithAttributesElement;

/**
 * A node in the tree. (don't confuse with Node* classes in org.gohtml).
 *
 * @author André D. Piske
 * @since 0.1 alpha
 * @version 0.2 alpha
 */
public class Node extends NodeWithAttributesElement {

    private List<Node> children;
    /// Filter will not be used.
    public static final int SELECT_MODE_DEFAULT = 0;
    /// Results will be AND'ed
    public static final int SELECT_MODE_AND = 1;
    /// Results will be OR'ed
    public static final int SELECT_MODE_OR = 2;
    /// Selector only.
    public static final int SELECT_MODE_SELECTOR_ONLY = 3;

    public Node(String name, AttributeSet attributes) {
        super(name, attributes);
        children = null;
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder();
        if (children != null) {
            for (Node node : children) {
                b.append(node.toString());
            }
        }
        return b.toString();
    }

    protected void addChild(Node child) {
        if (children == null) {
            children = new LinkedList<Node>();
        }
        children.add(child);
    }

    public List<Node> getChildren() {
        if (children == null) {
            return new LinkedList();
        }
        return children;
    }

    /**
     * Travels by this instance and all children instances.<br>
     * Every node will call NodeTravel.onNodeTravel(node).
     *
     * @param travel The "callback" object
     * @see org.gohtml.tree.NodeTravel
     */
    public void travel(NodeTravel travel) {
        if (travel.onNodeTravel(this) && children != null) {
            for (Node child : children) {
                child.travel(travel);
            }
        }
    }

    /**
     * Returns a list of nodes filtered by an user-defined filter function.<br>
     * <p>When {@code filter.onNode(node)} returns true, {@code node} will be added
     * to the resulting list.</p>
     *
     * @see org.gohtml.tree.NodeFilter
     * @return The list of filtered nodes. Will never return {@code null}
     */
    public List<Node> filter(final NodeFilter filter) {
        final List<Node> nodes = new LinkedList<Node>();
        travel(new NodeTravel() {

            public boolean onNodeTravel(Node node) {
                if (filter.filterNode(node)) {
                    nodes.add(node);
                }
                return true;
            }
        });
        return nodes;
    }

    private boolean internalSelect(Path brokenPath, int level, List<Node> nodeList, boolean deepInside) {
        boolean matches = Selector.nodeMatchesPath(this, brokenPath.getPiece(level));
        boolean childDeepInside = false;
        String nextSeparator = brokenPath.getSeparator(level);
        if (nextSeparator != null && nextSeparator.equals("/")) {
            childDeepInside = true;
        }

        if (matches) {
            if (level == brokenPath.getPieces().size() - 1) {
                nodeList.add(this);
                return true;
            } else if (null == children) {
                return false;
            } else {
                boolean r = false;
                for (Node child : children) {
                    if (child.internalSelect(brokenPath, level + 1, nodeList, childDeepInside)) {
                        r = true;
                    }
                }
                return r;
            }
        } else if (deepInside && children != null) {
            boolean r = false;
            for (Node child : children) {
                if (child.internalSelect(brokenPath, level, nodeList, childDeepInside)) {
                    r = true;
                }
            }
            return r;
        }
        return false;
    }

    public List<Node> select(String path) {
        return select(path, true);
    }

    public List<Node> select(String path, boolean deepInside) {
        List<Node> nodes = new LinkedList<Node>();
        Path brokenPath = Selector.breakPath(path);
        if (brokenPath == null) {
            return null;
        }
        if (internalSelect(brokenPath, 0, nodes, deepInside)) {
            return nodes;
        }
        return null;
    }
}
